const chalk = require('chalk')
const { isEmptyFolder, getFastOrder } = require('./utils')
const { execPromise } = require('./execsh')
const { createTemplate, pointingOrder } = require('./templates')
const semver = require('semver')
const { modifyTemplatePkg } = require('./file')

const { cmdMap, initQuestions, TemplateEdit, createTemplateFunc, delTemplateFunc, editTemplateFunc } = require('./config')
const path = require('path')
const projectPath = path.resolve(process.cwd())

async function run() {
    execPromise([
        { cmd: 'node -v', log: '>未检测到node，请安装node>=10！', tag: 'node' },
        { cmd: 'npm -v', log: '>未检测到npm，请安装npm>=6！', tag: 'npm' },
        // { cmd: 'test', log: '>未检测到test，请安装较新版本的test！' },
    ]).then(async(outs) => {
        /**
         * @function outs 这里返回的参数参考以下
         *  [ // 主要返回的是对应npm node的版本 
         *      { success: true, out: 'v14.0.0\r\n', tag: 'node' },
         *      { success: true, out: '6.14.4\n', tag: 'npm' }
         *  ]
         */
        const logs = outs.reduce((acc, cur) => {
            const { success, tag, out } = cur
            const version = cmdMap[tag]
            if (success && semver.satisfies(out, `< ${version}`)) {
                acc.push(chalk.red(`${tag}版本应该>=${version},请更新后重新运行！`))
            }
            return acc
        }, [])
        const basicWarning = chalk.yellow('运行环境检测失败->请根据输出信息配置运行环境，然后重新运行脚手架命令')
        if (outs.some((item) => !item.success)) {
            if (logs.length > 0) {
                logs.forEach((log) => console.log(log))
            }
        } else {
            let versions = await getFastOrder()
            let resultes = await pointingOrder(versions, projectPath) // 判断有指向性指令
            if (resultes) {
                return
            }
            let edits = await TemplateEdit()
            if (edits.edit.indexOf('生成模板') !== -1) { // 进行模板选择生成
                if (logs.length > 0) {
                    logs.forEach((log) => console.log(log))
                    console.log(basicWarning)
                    return
                }
                const isEmpty = await isEmptyFolder()
                if (isEmpty) {
                    await initQuestions((answer, pathUrls) => {
                        const { pathUrl, id } = pathUrls[answer.template]
                        if (id.length < 5) {
                            createTemplate(path.resolve(__dirname + pathUrl), projectPath, id)
                        } else {
                            createTemplate(path.resolve(pathUrl), projectPath, id)
                        }
                    })

                } else {
                    console.log(chalk.red('运行环境检测失败->请选择空文件夹重新运行'))
                }
            } else if (edits.edit.indexOf('修改模板') !== -1) { // 修改模板
                editTemplateFunc()
            } else if (edits.edit.indexOf('删除模板') !== -1) { // 删除模板
                delTemplateFunc()
            } else { // 进行模板接收和修改
                let creates = await createTemplateFunc()
                await modifyTemplatePkg(creates)
            }

        }
    })
}

module.exports = run